// 字符串的下划线格式转驼峰格式，eg：hello_world => helloWorld
const jsonToHump = async (ctx, next) => {
  ctx.write = (obj) => ctx.body = jsonToHumpFun(obj)
  await next()
}
// 下划线转驼峰
// JSON对象的key值转换为驼峰式 eg：{helloWorld:''} => { hello_world: '' } 
function underline2Hump (s) {
  return s.replace(/_(\w)/g, function (all, letter) {
    return letter.toUpperCase()
  })
}
function jsonToHumpFun (obj) {
  if (obj instanceof Array) {
    obj.forEach(function (v, i) {
      jsonToHumpFun(v)
    })
  } else if (obj instanceof Object) {
    Object.keys(obj).forEach(function (key) {
      var newKey = underline2Hump(key)
      if (newKey !== key) {
        obj[newKey] = obj[key]
        delete obj[key]
      }
      jsonToHumpFun(obj[newKey])
    })
  }
  return obj
}

// 驼峰转下划线
// 字符串的驼峰格式转下划线格式，eg：helloWorld => hello_world
function hump2Underline (s) {
  return s.replace(/([A-Z])/g, '_$1').toLowerCase()
}
// JSON对象的key值转换为下划线格式
function jsonToUnderline (obj) {
  if (obj instanceof Array) {
    obj.forEach(function (v, i) {
      jsonToUnderline(v)
    })
  } else if (obj instanceof Object) {
    Object.keys(obj).forEach(function (key) {
      var newKey = hump2Underline(key)
      if (newKey !== key) {
        obj[newKey] = obj[key]
        delete obj[key]
      }
      jsonToUnderline(obj[newKey])
    })
  }
  return obj
}

// 菜单级联数组
function getTreeOfArr (data, pid) {
  var newArr = []
  for (var i = 0; i < data.length; i++) {
    var item = data[i]
    if (item.parent_id == pid) {
      var obj = {}
      obj = {
        ...item
      }
      obj.children = getTreeOfArr(data, item.menu_id)
      newArr.push(obj)
    }
  }
  return newArr
}


module.exports = {
  jsonToHump,
  jsonToHumpFun,
  jsonToUnderline,
  getTreeOfArr
}